import * as bajaService from '@/services/bajaService';
import memoryUtils from '@/utils/memoryUtils';

const fetchSearchParams = async (searchParams, parentNode=null) => {
  const searchParamList = [];
  if (searchParams && searchParams.length > 0) {
    for (let i = 0; i < searchParams.length; i++) {
      const { $typeSpec } = searchParams[i].getType();
      if ($typeSpec.endsWith('SearchParamGroup')||$typeSpec.endsWith('EnergyArea')||$typeSpec.endsWith('EnergyCategory')) {
        const searchParamItems = await bajaService.fetchNavChildren(searchParams[i]);
        const node = {
          $handle: searchParams[i].$handle,
          $typeSpec,
          navOrd: searchParams[i].getNavOrd().toString(),
          title: searchParams[i].getTitle(),
          value: searchParams[i].$handle,
          key: searchParams[i].$handle,
          parent: parentNode,
        };
        if($typeSpec.endsWith('EnergyCategory')) {
          const { $ordinal } = searchParams[i].getEnergyCategoryType();
          node['energyCategoryType'] = memoryUtils.ENERGYCATEGORY_TYPE[$ordinal];
          node['price'] = searchParams[i].getPrice();
        }
        node.children = await fetchSearchParams(searchParamItems, node);
        searchParamList.push(node);
      } else if ($typeSpec.endsWith('SearchParamItem')) {
        searchParamList.push({
          $handle: searchParams[i].$handle,
          $typeSpec,
          navOrd: searchParams[i].getNavOrd().toString(),
          title: searchParams[i].getTitle(),
          value: searchParams[i].$handle,
          key: searchParams[i].$handle,
          historyOrds: [searchParams[i].getHistoryOrd().$ord],
          alarmClassOrd: searchParams[i].getAlarmClassOrd().$ord,
          parent: parentNode,
        });
      } else if ($typeSpec.endsWith('TreeMenuItem')) {
        const { $ordinal } = searchParams[i].getTreeMenuItemType();
        const node = {
          $handle: searchParams[i].$handle,
          $typeSpec,
          title: searchParams[i].getTitle(),
          nIcon: searchParams[i].getNIcon(),
          pagePath: searchParams[i].getPagePath(),
          url: searchParams[i].getUrl(),
          navOrd: searchParams[i].getNavOrd().toString(),
          treeMenuItemType: memoryUtils.TREEMENUITEM_TYPE[$ordinal],
          key: searchParams[i].$handle,
          parent: parentNode,
        }
        if(memoryUtils.TREEMENUITEM_TYPE[$ordinal] === 'SEARCH_PARAMS') {
          node.searchParams = await fetchSearchParamsFromOrd(searchParams[i].getNavOrd().toString());
        }
        searchParamList.push(node);
      }
    }
  }
  return Promise.resolve(searchParamList);
}

const fetchSearchParamsFromOrd = async (treeMenuOrd) => {
  let searchParams = [];
  const treeMenuItem = await bajaService.Ord(treeMenuOrd);
  if(treeMenuItem) {
    const { $ordinal } = treeMenuItem.getTreeMenuItemType();
    const treeMenuItemType = memoryUtils.TREEMENUITEM_TYPE[$ordinal];
    if(treeMenuItemType === 'SEARCH_PARAMS') {
      const navOrd = treeMenuItem.getNavOrd().toString();
      const searchParamRoot = await bajaService.Ord(navOrd+'/searchParamRoot');
      if(searchParamRoot) {
        searchParams = await bajaService.fetchNavChildren(searchParamRoot);
        searchParams = await fetchSearchParams(searchParams);
        if(!searchParams) {
          searchParams = []
        }
      }
    }
  }
  return searchParams;
}

const fetchDataTableFromOrd = async (treeMenuOrd) => {
  const dataTable = {};
  const treeMenuItem = await bajaService.Ord(treeMenuOrd);
  if(treeMenuItem) {
    const { $ordinal } = treeMenuItem.getTreeMenuItemType();
    const treeMenuItemType = memoryUtils.TREEMENUITEM_TYPE[$ordinal];
    if(treeMenuItemType === 'TABLE') {
      const navOrd = treeMenuItem.getNavOrd().toString();
      const dataTableRoot = await bajaService.Ord(navOrd+'/dataTableRoot');
      if(dataTableRoot) {
        dataTable['title'] = dataTableRoot.getTitle();
        const tableRows = await bajaService.fetchNavChildren(dataTableRoot);
        const tableRowList = [];
        if (tableRows && tableRows.length > 0) {
          for (let i = 0; i < tableRows.length; i++) {
            const cells = await bajaService.fetchNavChildren(tableRows[i]);
            const tableRow = {};
            if(cells && cells.length > 0) {
              tableRow['cells'] = cells.map(cell => {
                const { $ordinal } = cell.getTableCellType();
                if (JSON.stringify(memoryUtils.TABLECELL_TYPE) === '{}') {
                  const tableCellTypeExpose = cell.getTableCellTypeExpose();
                  const obj = JSON.parse(tableCellTypeExpose);
                  for (let key in obj) {
                    memoryUtils.TABLECELL_TYPE[obj[key]] = key;
                  }
                }
                return {
                  title: cell.getTitle(),
                  cellType: memoryUtils.TABLECELL_TYPE[$ordinal],
                  realtimeOrd: cell.getRealtimeOrd().$ord,
                }
              })

            }
            tableRowList.push(tableRow);
          }
        }
        dataTable['rows'] = tableRowList;
      }
    }
  }
  return dataTable;
}

export { fetchSearchParams, fetchSearchParamsFromOrd, fetchDataTableFromOrd };
